// 1. ------------------ 初始化剪裁框 ----------------------
let image = $('#image');
let option = {
    aspectRatio: 1,
    preview: '.img-preview'
};
image.cropper(option);

// 2. ---------------- 点击上传按钮,能够选择图片 -----------------
$('#chooseFile').on('click', function () {
    $('#file').trigger('click');
})

// 3. ------------------ 更换剪裁区的图片 ----------------------
$('#file').on('change',function () {
    // console.dir(this);
    if (this.files.length > 0) {
        let fileObj = this.files[0];
        let url = URL.createObjectURL(fileObj);
        image.cropper('replace', url);
    }
})

// 4. ------------------ 点击确定,剪裁图片,上传图片 ---------------
$('#sure').on('click', function () {
    // 剪裁图片
    let canvas = image.cropper('getCroppedCanvas', {width: 30, height: 30});
    // canvas是h5的画布,在Ajax提交之前,需要把canvas转成对应的格式
    let base64 = canvas.toDataURL();
    // console.log(base64);
    axios.post('/my/user/avatar', 'avatar=' + encodeURIComponent(base64)).then(res => {
        // console.log(res)
        if (res.data.status === 0) {
          layer.msg(res.data.message);
          window.parent.getUserInfo();
        }
      });
})